package nila;
import java.io.*;
import java.util.*;

interface I_Reader {
    // Get next character.
    char next();
    char peek();
    // mark the position in stream.
    void mark();
    // undo until marked position.
    void rollback();
    // switch the prompt to the given.
    void push_prompt(String v);
    void pop_prompt();
    boolean eof();
}

public class RConsole implements I_Reader {
    Stack<String> _prompts = null;
    StringBuffer _sb = null;
    int _read;
    int _mark;
    public static boolean debug = false;
    void d(String s) {
        if (debug) I.d("rconsole", s);
    }
    public RConsole() {
        _prompts =  new Stack<String>();
        _sb = new StringBuffer();
        _read = -1; // current point.
        _mark = _read;
    }

    public char next() {
        int sl = _sb.length() -1;
        if ( _read >= sl ) { // replenish the string buffer.
            String s = I.i(prompt());
            d(s);
            if (s == null) return '\0';
            _sb.append(s + "\n");
        }
        _read++;
        return _sb.charAt(_read);
    }

    public char peek() {
        int sl = _sb.length() -1;
        if ( _read >= sl ) { // replenish the string buffer.
            String s = I.i(prompt());
            d("(peek)" + s);
            if (s == null) return '\0';
            _sb.append(s + "\n");
        }
        return _sb.charAt(_read + 1);
    }

    public void mark(){
        _mark = _read;
    }
    public void rollback(){
        _read = _mark;
    }
    public void push_prompt(String v){
        _prompts.push(v);
    }
    public void pop_prompt(){
        _prompts.pop();
    }
    String prompt() {
        return _prompts.peek();
    }
    public boolean eof() {
        return false;
    }
}

